import React, { PureComponent } from 'react';
import { getStrLength } from 'utils';
import styles from './style.less';

// 本页的1em == 14px
const em = 14; // px

const getWidth = str => (str ? getStrLength(`${str}`) * 0.5 : 0) + 2;

class index extends PureComponent {
  onRowPress = row => {};

  isMount = false;

  columns = [];

  totalWidth = 0;

  tableRef = {};

  state = {
    time: null,
  };

  constructor(props) {
    super(props);
    const { onRowPress = () => {} } = props;
    this.onRowPress = onRowPress;
    this.setColumns();
  }

  componentDidMount() {
    this.isMount = true;
    this.adjustWidth();
  }

  componentDidUpdate(prevProps, prevState, snapshot) {}

  getSnapshotBeforeUpdate(prevProps, prevState) {
    const { dimensionList: prevDimensionList, measureList: prevMeasureList } = prevProps;
    const { dimensionList, measureList } = this.props;
    // 字段变了时重新修改 columns
    if (
      JSON.stringify(prevDimensionList) !== JSON.stringify(dimensionList) ||
      JSON.stringify(prevMeasureList) !== JSON.stringify(measureList)
    ) {
      this.setColumns();
    }
    return null;
  }

  // 调整宽度
  adjustWidth = () => {
    const { clientWidth = 0 } = this.tableRef;
    const totalWPx = this.totalWidth * em;
    let change = 1;

    if (totalWPx < clientWidth) {
      change = clientWidth / totalWPx;
      this.totalWidth *= change;
    }
    for (const col of this.columns) {
      col.width = col.width * change;
    }
  };

  setColumns = () => {
    const { dimensionList = [], measureList = [], sourceData = [] } = this.props;
    // getStrLength
    const columns = [...dimensionList, ...measureList].map(({ key, label }) => ({
      title: label,
      key,
      width: getWidth(label),
    }));

    for (const rows of sourceData) {
      for (const col of columns) {
        const itemData = rows.find(r => r.Key === col.key);
        const _width = getWidth(itemData.Value);
        col.width = col.width > _width ? col.width : _width;
      }
    }

    this.totalWidth = columns.reduce((t, item) => t + item.width, 0);
    this.columns = columns;

    setTimeout(() => {
      if (this.isMount) {
        this.setState({
          time: new Date().getTime(),
        });
      }
    });
  };

  renderTHead = () => (
    <div className={styles.tr} style={{ minWidth: `${this.totalWidth}em` }}>
      {this.columns.map(c => (
        <div className={styles.th} key={c.key} style={{ minWidth: `${c.width}em` }}>
          {c.title}
        </div>
      ))}
    </div>
  );

  renderTBody = () => {
    const { sourceData = [] } = this.props;

    return sourceData.map((row, index) => (
      <div className={styles.tr} key={JSON.stringify(row)} onClick={() => this.onRowPress(row)}>
        {this.columns.map(c => {
          const _rowData = row.find(item => item.Key === c.key) || {};
          return (
            <div className={styles.td} key={c.key} style={{ minWidth: `${c.width}em` }}>
              {_rowData.Value}
            </div>
          );
        })}
      </div>
    ));
  };

  render() {
    return (
      <div className={styles['table']} ref={e => (this.tableRef = e)}>
        <div className={styles.thead} style={{ minWidth: `${this.totalWidth}em` }}>
          {this.renderTHead()}
        </div>
        <div className={styles.tbody} style={{ minWidth: `${this.totalWidth}em` }}>
          {this.renderTBody()}
        </div>
      </div>
    );
  }
}

export default index;
